package com.study.config;

import com.study.bean.ConnectionFactoryBean;
import com.study.bean.User;
import com.study.dao.UserDAO;
import com.study.dao.UserDAOImpl;
import com.study.service.UserService;
import com.study.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Configuration
@PropertySource("classpath:init.properties")
public class AppConfig {

    @Value("${id}")
    private Integer id;
    @Value("${name}")
    private String name;

    @Bean("u")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public User user() {
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }

    @Bean
    public Connection conn() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring5_mysql?useSSL=false", "root", "123456");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    @Bean
    public Connection conn1() {
        ConnectionFactoryBean connectionFactoryBean = new ConnectionFactoryBean();
        Connection conn1 = null;
        try {
            conn1 = connectionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn1;
    }

    @Bean
    public UserDAO userDAO() {
        return new UserDAOImpl();
    }

    @Bean
    public UserDAO userDAO2() {
        return new UserDAOImpl();
    }

    /**
     * 如果有形参，则会根据类型自动注入，如果类型相同，就根据名字，都找不到就报错
     * @param userDAO
     * @param userDAO2
     * @return
     */
    @Bean
    public UserService userService(UserDAO userDAO, UserDAO userDAO2) {
        UserServiceImpl userService = new UserServiceImpl();
        userService.setUserDAO(userDAO);
        return userService;
    }

}
